# -*- coding: utf-8 -*-
"""
@Project ：weather 
@File    ：weather_info.py
@Author: guzain
@Date:  2025/7/7 11:32:29
@Email： GZA5210@163.com
@Description: 天气信息获取模块
"""
import requests
from utils.log_config import logger
from services.weather_constants import (
    IPINFO_API_URL, TIANAPI_IPQUERY_URL, TIANAPI_KEY,
    WEATHER_API_BASE_URL, DEFAULT_CITY_ID, get_clean_weather_key
)
from config.config import USE_NETWORK_CITY, FIXED_CITY, CITY_ID_MAP


DEFAULT_CITY = "北京"  # 默认城市名称


def Get_city_from_ip():
    """获取IP地址所在城市"""
    try:
        # 使用ipinfo.io API获取IP地址信息
        response = requests.get(IPINFO_API_URL, timeout=5)
        data = response.json()
        logger.info(f"当前IP地址: {data.get('ip')}")
        response = requests.get(
            f'{TIANAPI_IPQUERY_URL}?ip={data["ip"]}&key={TIANAPI_KEY}&full=1',
            timeout=5
        )
        data = response.json()
        if data.get("code") == 200 and data.get("result"):
            msg = data.get("result", {}).get("city", "未知")
            logger.info(f"获取城市信息成功: {msg}")
            return msg
        else:
            logger.error(f"IP查询API返回错误: {data}")
            return DEFAULT_CITY
    except Exception as e:
        logger.error(f"获取IP地址失败: {e}", exc_info=True)
        return DEFAULT_CITY  # 使用默认城市


def Get_location(city):
    """获取当前天气地区id"""
    try:
        # 首先检查城市是否在City.ini中
        if city in CITY_ID_MAP:
            location_id = CITY_ID_MAP[city]
            logger.info(f"从City.ini获取城市location成功: {location_id}")
            return location_id
        
        # 如果不在City.ini中，调用API获取
        clean_weather_key = get_clean_weather_key()
        weather_city_url = f'{WEATHER_API_BASE_URL}/geo/city/lookup?key={clean_weather_key}&location={city}'
        logger.info(f"正在请求地区ID: {weather_city_url}")
        response = requests.get(weather_city_url)
        logger.info(f"响应状态码: {response.status_code}")
        logger.debug(f"响应头: {response.headers}")
        city_json = response.json()
        # 直接打印完整响应以便调试
        logger.debug(f"和风天气API响应: {city_json}")
        city_code = city_json.get("code")
        if city_code == "200":
            for weather_city in city_json.get("location", []):
                city_id = weather_city.get("id", "未知")
                logger.info(f"通过API获取地区ID成功，ID：{city_id}")
                return city_id
        else:
            logger.error(f"访问获取地区ID接口失败，错误码：{city_code}，响应：{city_json}")
            # 如果API获取失败，检查默认城市是否在City.ini中
            if DEFAULT_CITY in CITY_ID_MAP:
                return CITY_ID_MAP[DEFAULT_CITY]
            # 使用默认城市ID（北京）作为备选
            logger.info(f"使用默认城市ID：{DEFAULT_CITY_ID}（北京）")
            return DEFAULT_CITY_ID
    except Exception as e:
        logger.error(f"获取地区ID失败：{e}", exc_info=True)
        # 如果发生异常，检查默认城市是否在City.ini中
        if DEFAULT_CITY in CITY_ID_MAP:
            return CITY_ID_MAP[DEFAULT_CITY]
        # 使用默认城市ID（北京）作为备选
        logger.info(f"使用默认城市ID：{DEFAULT_CITY_ID}（北京）")
        return DEFAULT_CITY_ID

# 根据配置决定使用网络获取城市还是固定城市
if USE_NETWORK_CITY:
    city = Get_city_from_ip()
    logger.info(f"使用网络获取城市: {city}")
else:
    city = FIXED_CITY
    logger.info(f"使用配置的固定城市: {city}")

# 获取城市ID
CITY_ID = Get_location(city)
